<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/logo.jpg">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.jpg">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.jpg">
  <link rel="mask-icon" href="/images/logo.jpg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"www.doubeecat.ga","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"right"},"copycode":{"enable":true,"show_result":true,"style":"flat"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="树链剖分是个很强的 OIer 树链剖分是用来解决一系列树上问题的利器。">
<meta property="og:type" content="article">
<meta property="og:title" content="树链剖分 学习笔记">
<meta property="og:url" content="https://www.doubeecat.ga/2019/08/26/%E6%A0%91%E9%93%BE%E5%89%96%E5%88%86-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="Doubeecat&#39;s Blog">
<meta property="og:description" content="树链剖分是个很强的 OIer 树链剖分是用来解决一系列树上问题的利器。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s2.ax1x.com/2019/08/25/m2dRDe.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/08/25/m2wsaj.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/08/25/m2vk9J.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/08/25/m2vA39.png">
<meta property="article:published_time" content="2019-08-25T16:04:50.000Z">
<meta property="article:modified_time" content="2020-07-31T09:00:05.024Z">
<meta property="article:author" content="Doubeecat">
<meta property="article:tag" content="图论">
<meta property="article:tag" content="树链剖分">
<meta property="article:tag" content="树">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s2.ax1x.com/2019/08/25/m2dRDe.png">

<link rel="canonical" href="https://www.doubeecat.ga/2019/08/26/%E6%A0%91%E9%93%BE%E5%89%96%E5%88%86-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>树链剖分 学习笔记 | Doubeecat's Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Doubeecat's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">“即便前路混沌，同她走过，才算人间。”</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/aboutme/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-2020-届招新">

    <a href="/new-oier-wanted/" rel="section"><i class="fa fa-calendar fa-fw"></i>2020 届招新</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://www.doubeecat.ga/2019/08/26/%E6%A0%91%E9%93%BE%E5%89%96%E5%88%86-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/logo.jpg">
      <meta itemprop="name" content="Doubeecat">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Doubeecat's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          树链剖分 学习笔记
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-08-26 00:04:50" itemprop="dateCreated datePublished" datetime="2019-08-26T00:04:50+08:00">2019-08-26</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-31 17:00:05" itemprop="dateModified" datetime="2020-07-31T17:00:05+08:00">2020-07-31</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index"><span itemprop="name">学习笔记</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2019/08/26/%E6%A0%91%E9%93%BE%E5%89%96%E5%88%86-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2019/08/26/%E6%A0%91%E9%93%BE%E5%89%96%E5%88%86-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>7.3k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>7 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><del>树链剖分是个很强的 OIer</del></p>
<p>树链剖分是用来解决一系列树上问题的利器。<br><a id="more"></a></p>
<h2 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h2><ul>
<li>链：树上不拐弯的一条路径</li>
<li>重儿子：子树大小最大的儿子</li>
<li>轻儿子：其他儿子</li>
<li>重链：由重儿子组成的链</li>
</ul>
<h2 id="结果和过程"><a href="#结果和过程" class="headerlink" title="结果和过程"></a>结果和过程</h2><h3 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h3><p>这是原树</p>
<p><img src="https://s2.ax1x.com/2019/08/25/m2dRDe.png" alt=""></p>
<p>剖分之后的树</p>
<p><img src="https://s2.ax1x.com/2019/08/25/m2wsaj.png" alt=""></p>
<p>这里，<strong>红色的边</strong>构成重链，<strong>蓝色的点</strong>为重儿子，<strong>绿色的点</strong>为轻儿子。</p>
<p>注意，这里的 7 号与 8 号节点子树大小相同，因此我们选择<strong>编号靠前</strong>的儿子为重儿子。</p>
<h3 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h3><p>一般来说，树链剖分通过两遍 dfs 来实现。</p>
<h4 id="定义-1"><a href="#定义-1" class="headerlink" title="定义"></a>定义</h4><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">siz[x] <span class="comment">//子树x的大小</span></span><br><span class="line">top[x] <span class="comment">//x所在链的顶端</span></span><br><span class="line">fat[x] <span class="comment">//x的父亲</span></span><br><span class="line">dep[x] <span class="comment">//x的深度</span></span><br><span class="line">son[x] <span class="comment">//x的重儿子</span></span><br></pre></td></tr></table></figure>
<p>第一遍 dfs ，我们先处理出每个节点的<strong>父亲</strong>，<strong>深度</strong>，<strong>子树大小</strong>，<strong>重儿子</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs1</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> f)</span> </span>&#123;</span><br><span class="line">	siz[u] = <span class="number">1</span>;</span><br><span class="line">	dep[u] = dep[f] + <span class="number">1</span>;</span><br><span class="line">	son[u] = <span class="number">0</span>;</span><br><span class="line">	fat[u] = f;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = hd[u];i;i= nxt[i]) &#123;</span><br><span class="line">		<span class="keyword">int</span> v = to[i];</span><br><span class="line">		<span class="keyword">if</span> (v != f) &#123;</span><br><span class="line">			dfs1(v,u);</span><br><span class="line">			siz[u] += siz[v];</span><br><span class="line">			<span class="keyword">if</span> (siz[v] &gt; siz[son[u]]) &#123;</span><br><span class="line">				son[u] = v;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第二遍 dfs，我们处理出每条链<strong>链顶的节点</strong>，</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs2</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> f)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (son[f] == u) &#123;</span><br><span class="line">		top[u] = top[f];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		top[u] = u;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (son[u]) &#123;</span><br><span class="line">		dfs2(son[u],u);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = hd[u];i;i = nxt[i]) &#123;</span><br><span class="line">		<span class="keyword">int</span> v = to[i];</span><br><span class="line">		<span class="keyword">if</span> (v != f &amp;&amp; v != son[u]) &#123;</span><br><span class="line">			dfs2(v,u);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样树链剖分的基本结构就写完辣！<del>是不是很简单</del></p>
<h3 id="应用"><a href="#应用" class="headerlink" title="应用"></a>应用</h3><h4 id="LCA"><a href="#LCA" class="headerlink" title="LCA"></a>LCA</h4><p>显然，我们可以发现，在一条重链上的两个节点的 LCA 显然就是深度更浅的那个节点。</p>
<p>所以我们可以先将两个节点跳到同一条链上，求出深度浅的那个节点即可，于是有了如下代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">lca</span><span class="params">(<span class="keyword">int</span> a,<span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> ta = top[a],tb = top[b];ta != tb;) &#123;</span><br><span class="line">		<span class="keyword">if</span> (dep[ta] &gt; dep[tb]) &#123;</span><br><span class="line">			ta = top[a = fat[ta]];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			tb = top[b = fat[tb]];</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> dep[a] &lt; dep[b] ? a : b;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>时间复杂度$O(\log{n})$</p>
<p>例题：<a href="https://www.luogu.org/problem/P3379" target="_blank" rel="noopener">板子题</a></p>
<p>随手套个板子写掉。</p>
<p>代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cctype&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cstring&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> N = <span class="number">500010</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> M = N &lt;&lt; <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">int</span> <span class="title">read</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">char</span> v = getchar();<span class="keyword">int</span> x = <span class="number">0</span>,f = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">while</span> (!<span class="built_in">isdigit</span>(v)) &#123;<span class="keyword">if</span> (v == <span class="string">'-'</span>)f = <span class="number">-1</span>;v = getchar();&#125;</span><br><span class="line">	<span class="keyword">while</span> (<span class="built_in">isdigit</span>(v)) &#123;x = x * <span class="number">10</span> + v - <span class="number">48</span>;v = getchar();&#125;</span><br><span class="line">	<span class="keyword">return</span> x * f;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> hd[N],edg[M],nxt[M],to[M],n,m,tot,cnt;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> v,<span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">	to[++tot] = v;edg[tot] = w;nxt[tot] = hd[u];hd[u] = tot;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="title">addedge</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> v,<span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">	add(u,v,w);add(v,u,w);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> dfn[N],top[N],fat[N],siz[N],son[N],end[N],dep[N],s;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs1</span><span class="params">(<span class="keyword">int</span> s,<span class="keyword">int</span> f)</span> </span>&#123;</span><br><span class="line">	son[s] = <span class="number">0</span>;</span><br><span class="line">	dep[s] = dep[f] + <span class="number">1</span>;</span><br><span class="line">	siz[s] = <span class="number">1</span>;</span><br><span class="line">	fat[s] = f;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = hd[s];i;i = nxt[i]) &#123;</span><br><span class="line">		<span class="keyword">if</span> (to[i] != f) &#123;</span><br><span class="line">			dfs1(to[i],s);</span><br><span class="line">			siz[s] += siz[to[i]];</span><br><span class="line">			<span class="keyword">if</span> (siz[to[i]] &gt; siz[son[s]]) &#123;</span><br><span class="line">				son[s] = to[i];</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs2</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> f)</span> </span>&#123;</span><br><span class="line">	dfn[u] = ++cnt;</span><br><span class="line">	<span class="keyword">if</span> (u == son[f]) &#123;</span><br><span class="line">		top[u] = top[f];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		top[u] = u;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (son[u]) &#123;</span><br><span class="line">		dfs2(son[u],u);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = hd[u];i;i = nxt[i]) &#123;</span><br><span class="line">		<span class="keyword">int</span> v = to[i];</span><br><span class="line">		<span class="keyword">if</span> (v != f &amp;&amp; v != son[u]) &#123;</span><br><span class="line">			dfs2(v,u);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	end[u] = cnt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">lca</span><span class="params">(<span class="keyword">int</span> a,<span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> ta = top[a],tb = top[b];ta != tb;) &#123;</span><br><span class="line">		<span class="keyword">if</span> (dep[ta] &gt; dep[tb]) &#123;</span><br><span class="line">			ta = top[a = fat[ta]];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			tb = top[b = fat[tb]];</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> dep[a] &lt; dep[b] ? a : b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	n = read(),m = read(),s = read();</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>;i &lt; n;++i) &#123;</span><br><span class="line">		<span class="keyword">int</span> u = read(),v = read(),w = <span class="number">1</span>;</span><br><span class="line">		addedge(u,v,w);</span><br><span class="line">	&#125;</span><br><span class="line">	dfs1(s,<span class="number">0</span>);</span><br><span class="line">	dfs2(s,<span class="number">0</span>);</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>;i &lt;= m;++i) &#123;</span><br><span class="line">		<span class="keyword">int</span> u = read(),v = read();</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">"%d\n"</span>,lca(u,v));</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="链上修改，子树修改"><a href="#链上修改，子树修改" class="headerlink" title="链上修改，子树修改"></a>链上修改，子树修改</h4><p>这里就必须引出一个新东西了：dfs 序</p>
<p>指的是第几次 dfs 遍历到的这个节点</p>
<p>定义数组<code>dfn[x]</code>为节点 x 的 dfs 序。</p>
<p>我们可以在 <code>dfs2</code> 中顺手维护一下。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs2</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> f)</span> </span>&#123;</span><br><span class="line">	dfn[u] = ++cnt;</span><br><span class="line">	<span class="keyword">if</span> (son[f] == u) &#123;</span><br><span class="line">		top[u] = top[f];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		top[u] = u;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (son)</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = hd[u];i;i = nxt[i]) &#123;</span><br><span class="line">		<span class="keyword">int</span> v = to[i];</span><br><span class="line">		<span class="keyword">if</span> (v != f) &#123;</span><br><span class="line">			dfs2(v,u);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	end[cnt] = u;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里给出每个节点加上 <code>dfn</code> 的图</p>
<p><img src="https://s2.ax1x.com/2019/08/25/m2vk9J.png" alt=""></p>
<p>我们可以发现，在每棵<strong>子树</strong>，每条<strong>链</strong>上的dfn都是连续的！</p>
<p>这样看可能不太明朗，我们把它转化成区间来看（这里是子树的，链同理）</p>
<p><img src="https://s2.ax1x.com/2019/08/25/m2vA39.png" alt=""></p>
<p>所以我们就可以利用数据结构维护一下节点了。</p>
<p>对子树修改就是 <code>change(dfn[x],dfn[x]+siz[x]-1)</code></p>
<p>链上修改就是 <code>change(dfn[x],dfn[y])</code></p>
<p>这里的核心思想是：将树上问题转化成序列问题来处理</p>
<p>例题：<a href="https://www.luogu.org/problem/P2590" target="_blank" rel="noopener">[ZJOI2008]树的统计</a></p>
<p>用线段树维护最大值最小值。</p>
<p>代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">6</span><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cctype&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string&gt;</span></span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> N = <span class="number">100010</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> M = N &lt;&lt; <span class="number">1</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> INF = <span class="number">0x3f3f3f3f</span>;</span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">int</span> <span class="title">read</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">char</span> v = getchar();<span class="keyword">int</span> x = <span class="number">0</span>,f = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">while</span> (!<span class="built_in">isdigit</span>(v)) &#123;<span class="keyword">if</span> (v == <span class="string">'-'</span>)f = <span class="number">-1</span>;v = getchar();&#125;</span><br><span class="line">	<span class="keyword">while</span> (<span class="built_in">isdigit</span>(v)) &#123;x = x * <span class="number">10</span> + v - <span class="number">48</span>;v = getchar();&#125;</span><br><span class="line">	<span class="keyword">return</span> x * f;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> to[M],hd[N],nxt[M],tot;</span><br><span class="line"><span class="built_in">string</span> s;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">	to[++tot] = v;nxt[tot] = hd[u];hd[u] = tot;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="title">addedge</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">	add(u,v);add(v,u);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> dfn[N],top[N],fat[N],siz[N],dep[N],son[N],rk[N],cnt,n;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs1</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> f)</span> </span>&#123;</span><br><span class="line">	fat[u] = f;</span><br><span class="line">	dep[u] = dep[f] + <span class="number">1</span>;</span><br><span class="line">	son[u] = <span class="number">0</span>;</span><br><span class="line">	siz[u] = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = hd[u];i;i = nxt[i]) &#123;</span><br><span class="line">		<span class="keyword">int</span> v = to[i];</span><br><span class="line">		<span class="keyword">if</span> (v != f) &#123;</span><br><span class="line">			dfs1(v,u);</span><br><span class="line">			siz[u] += siz[v];</span><br><span class="line">			<span class="keyword">if</span> (siz[v] &gt; siz[son[u]]) &#123;</span><br><span class="line">				son[u] = v;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dfs2</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> f)</span> </span>&#123;</span><br><span class="line">	dfn[u] = ++cnt;rk[cnt] = u;</span><br><span class="line">	<span class="keyword">if</span> (son[f] == u) &#123;</span><br><span class="line">		top[u] = top[f];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		top[u] = u;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (son[u]) &#123;</span><br><span class="line">		dfs2(son[u],u);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = hd[u];i;i = nxt[i]) &#123;</span><br><span class="line">		<span class="keyword">int</span> v = to[i];</span><br><span class="line">		<span class="keyword">if</span> (v != f &amp;&amp; v != son[u]) &#123;</span><br><span class="line">			dfs2(v,u);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> num[N];</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">node</span> &#123;</span></span><br><span class="line">	<span class="keyword">int</span> l,r,big,sum;</span><br><span class="line">&#125;tree[N&lt;&lt;<span class="number">2</span>];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="title">build</span><span class="params">(<span class="keyword">int</span> p,<span class="keyword">int</span> l,<span class="keyword">int</span> r)</span> </span>&#123;</span><br><span class="line">	tree[p].l = l;tree[p].r = r;</span><br><span class="line">	<span class="keyword">if</span> (l == r) &#123;</span><br><span class="line">		tree[p].big = tree[p].sum = num[rk[l]];</span><br><span class="line">		<span class="keyword">return</span> ;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> mid = (l + r) &gt;&gt; <span class="number">1</span>;</span><br><span class="line">	build(p &lt;&lt; <span class="number">1</span>,l,mid);</span><br><span class="line">	build(p &lt;&lt; <span class="number">1</span>|<span class="number">1</span>,mid+<span class="number">1</span>,r);</span><br><span class="line">	tree[p].sum = tree[p&lt;&lt;<span class="number">1</span>].sum + tree[p&lt;&lt;<span class="number">1</span>|<span class="number">1</span>].sum;</span><br><span class="line">	tree[p].big = max(tree[p&lt;&lt;<span class="number">1</span>].big,tree[p&lt;&lt;<span class="number">1</span>|<span class="number">1</span>].big);</span><br><span class="line">	<span class="keyword">return</span> ;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="title">modify</span><span class="params">(<span class="keyword">int</span> p,<span class="keyword">int</span> x,<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (tree[p].l == tree[p].r) &#123;</span><br><span class="line">		tree[p].sum = tree[p].big = v;</span><br><span class="line">		<span class="keyword">return</span> ;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> mid = (tree[p].l + tree[p].r) &gt;&gt; <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">if</span> (x &lt;= mid) modify(p&lt;&lt;<span class="number">1</span>,x,v);</span><br><span class="line">	<span class="keyword">if</span> (x &gt; mid) modify(p&lt;&lt;<span class="number">1</span>|<span class="number">1</span>,x,v);</span><br><span class="line">	tree[p].sum = tree[p&lt;&lt;<span class="number">1</span>].sum + tree[p&lt;&lt;<span class="number">1</span>|<span class="number">1</span>].sum;</span><br><span class="line">	tree[p].big = max(tree[p&lt;&lt;<span class="number">1</span>].big,tree[p&lt;&lt;<span class="number">1</span>|<span class="number">1</span>].big);</span><br><span class="line">	<span class="keyword">return</span> ;</span><br><span class="line">&#125; </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">int</span> <span class="title">querym</span><span class="params">(<span class="keyword">int</span> p,<span class="keyword">int</span> x,<span class="keyword">int</span> y)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (tree[p].l &gt;= x &amp;&amp; tree[p].r &lt;= y) &#123;</span><br><span class="line">		<span class="keyword">return</span> tree[p].big;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> mid = (tree[p].l + tree[p].r) &gt;&gt; <span class="number">1</span>,ans = -INF;</span><br><span class="line">	<span class="keyword">if</span> (x &lt;= mid) &#123;</span><br><span class="line">		ans = max(ans,querym(p&lt;&lt;<span class="number">1</span>,x,y));</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (y &gt; mid) &#123;</span><br><span class="line">		ans = max(ans,querym(p&lt;&lt;<span class="number">1</span>|<span class="number">1</span>,x,y));</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">int</span> <span class="title">querys</span><span class="params">(<span class="keyword">int</span> p,<span class="keyword">int</span> x,<span class="keyword">int</span> y)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (tree[p].l &gt;= x &amp;&amp; tree[p].r &lt;= y) &#123;</span><br><span class="line">		<span class="keyword">return</span> tree[p].sum;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> mid = (tree[p].l + tree[p].r) &gt;&gt; <span class="number">1</span>,ans = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">if</span> (x &lt;= mid) &#123;</span><br><span class="line">		ans += querys(p&lt;&lt;<span class="number">1</span>,x,y);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (y &gt; mid) &#123;</span><br><span class="line">		ans += querys(p&lt;&lt;<span class="number">1</span>|<span class="number">1</span>,x,y);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span> <span class="title">change</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> t)</span> </span>&#123;</span><br><span class="line">	modify(<span class="number">1</span>,dfn[u],t);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">int</span> <span class="title">qmax</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> ans = -INF;</span><br><span class="line">	<span class="keyword">while</span> (top[u] != top[v]) &#123;</span><br><span class="line">		<span class="keyword">if</span> (dep[top[u]] &lt; dep[top[v]]) &#123;</span><br><span class="line">			swap(u,v);</span><br><span class="line">		&#125;</span><br><span class="line">		ans = max(ans,querym(<span class="number">1</span>,dfn[top[u]],dfn[u]));</span><br><span class="line">		u = fat[top[u]];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (dep[u] &gt; dep[v]) &#123;</span><br><span class="line">		swap(u,v);</span><br><span class="line">	&#125;</span><br><span class="line">	ans = max(ans,querym(<span class="number">1</span>,dfn[u],dfn[v]));</span><br><span class="line">	<span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">int</span> <span class="title">qsum</span><span class="params">(<span class="keyword">int</span> u,<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> ans = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">while</span> (top[u] != top[v]) &#123;</span><br><span class="line">		<span class="keyword">if</span> (dep[top[u]] &lt; dep[top[v]]) &#123;</span><br><span class="line">			swap(u,v);</span><br><span class="line">		&#125;</span><br><span class="line">		ans += querys(<span class="number">1</span>,dfn[top[u]],dfn[u]);</span><br><span class="line">		u = fat[top[u]];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (dep[u] &gt; dep[v]) &#123;</span><br><span class="line">		swap(u,v);</span><br><span class="line">	&#125;</span><br><span class="line">	ans += querys(<span class="number">1</span>,dfn[u],dfn[v]);</span><br><span class="line">	<span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">signed</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	n = read();</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>;i &lt; n;++i) &#123;</span><br><span class="line">		addedge(read(),read());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>;i &lt;= n;++i) &#123;</span><br><span class="line">		num[i] = read();</span><br><span class="line">	&#125;</span><br><span class="line">	dfs1(<span class="number">1</span>,<span class="number">0</span>);dfs2(<span class="number">1</span>,<span class="number">0</span>);build(<span class="number">1</span>,<span class="number">1</span>,n);</span><br><span class="line">	<span class="keyword">int</span> m = read();</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>;i &lt;= m;++i) &#123;</span><br><span class="line">		<span class="built_in">cin</span> &gt;&gt; s;</span><br><span class="line">		<span class="keyword">int</span> u = read(),v = read();</span><br><span class="line">		<span class="keyword">if</span> (s == <span class="string">"CHANGE"</span>) &#123;</span><br><span class="line">			change(u,v);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (s == <span class="string">"QSUM"</span>) &#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">"%d\n"</span>,qsum(u,v));</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (s == <span class="string">"QMAX"</span>) &#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">"%d\n"</span>,qmax(u,v));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="练习"><a href="#练习" class="headerlink" title="练习"></a>练习</h2><p><a href="https://www.luogu.org/problem/P4114" target="_blank" rel="noopener">Qtree </a>把边权变成点权，巧妙的做法</p>
<p><a href="https://www.luogu.org/problem/P3178" target="_blank" rel="noopener">[HAOI2015]树上操作</a> 练手，区间修改，区间查询</p>
<p><a href="https://www.luogu.org/problem/P3258" target="_blank" rel="noopener">[JLOI2014]松鼠的新家</a> 巧妙的做法，也可以用树上差分来写</p>
<p><a href="https://www.luogu.org/problem/P2146" target="_blank" rel="noopener">[NOI2015]程序包管理器</a> 稍微转换一下问题</p>
<h2 id="后记"><a href="#后记" class="headerlink" title="后记"></a>后记</h2><p>感谢 <a href="https://minagami.github.io/" target="_blank" rel="noopener">$\color{black}M\color{red}{inagami}$</a> 给我提供了极大的帮助，感谢 <a href="http://yousiki.github.io/" target="_blank" rel="noopener">$\color{black}Y\color{red}{ouSiKi}$</a> 的教导</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%9B%BE%E8%AE%BA/" rel="tag"># 图论</a>
              <a href="/tags/%E6%A0%91%E9%93%BE%E5%89%96%E5%88%86/" rel="tag"># 树链剖分</a>
              <a href="/tags/%E6%A0%91/" rel="tag"># 树</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/08/22/CodeForcesRound-1206%E9%A2%98%E8%A7%A3/" rel="prev" title="CodeForcesRound#1206题解">
      <i class="fa fa-chevron-left"></i> CodeForcesRound#1206题解
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/09/07/Luogu%20P4999%20%E7%83%A6%E4%BA%BA%E7%9A%84%E6%95%B0%E5%AD%A6%E4%BD%9C%E4%B8%9A%20%E8%A7%A3%E9%A2%98%E6%8A%A5%E5%91%8A/" rel="next" title="Luogu P4999 烦人的数学作业 解题报告">
      Luogu P4999 烦人的数学作业 解题报告 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#定义"><span class="nav-number">1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结果和过程"><span class="nav-number">2.</span> <span class="nav-text">结果和过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#结果"><span class="nav-number">2.1.</span> <span class="nav-text">结果</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实现"><span class="nav-number">2.2.</span> <span class="nav-text">实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#定义-1"><span class="nav-number">2.2.1.</span> <span class="nav-text">定义</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#应用"><span class="nav-number">2.3.</span> <span class="nav-text">应用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#LCA"><span class="nav-number">2.3.1.</span> <span class="nav-text">LCA</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#链上修改，子树修改"><span class="nav-number">2.3.2.</span> <span class="nav-text">链上修改，子树修改</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#练习"><span class="nav-number">3.</span> <span class="nav-text">练习</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后记"><span class="nav-number">4.</span> <span class="nav-text">后记</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Doubeecat"
      src="/images/logo.jpg">
  <p class="site-author-name" itemprop="name">Doubeecat</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">35</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">41</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/doubeecat" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;doubeecat" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:doubeecat@qq.com" title="E-Mail → mailto:doubeecat@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/5884458071" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;5884458071" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://oierwanhong.cc/" title="https:&#x2F;&#x2F;oierwanhong.cc" rel="noopener" target="_blank">Wh's Blog</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://blog.csdn.net/weixin_42750325" title="https:&#x2F;&#x2F;blog.csdn.net&#x2F;weixin_42750325" rel="noopener" target="_blank">Young_Zn_Cu's Blog</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2019 – 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-battery-full"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Doubeecat</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">89k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">1:21</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  
      

<script>
  if (typeof MathJax === 'undefined') {
    window.MathJax = {
      loader: {
        source: {
          '[tex]/amsCd': '[tex]/amscd',
          '[tex]/AMScd': '[tex]/amscd'
        }
      },
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
        tags: 'ams'
      },
      options: {
        renderActions: {
          findScript: [10, doc => {
            document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
              const display = !!node.type.match(/; *mode=display/);
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            });
          }, '', false],
          insertedScript: [200, () => {
            document.querySelectorAll('mjx-container').forEach(node => {
              let target = node.parentNode;
              if (target.nodeName.toLowerCase() === 'li') {
                target.parentNode.classList.add('has-jax');
              }
            });
          }, '', false]
        }
      }
    };
    (function () {
      var script = document.createElement('script');
      script.src = '//cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
      script.defer = true;
      document.head.appendChild(script);
    })();
  } else {
    MathJax.startup.document.state(0);
    MathJax.texReset();
    MathJax.typeset();
  }
</script>

    

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : '6CGcUDbuD17aESA6Abl5FcK8-gzGzoHsz',
      appKey     : 'dopf8aMzWSSVJbvbge6BmWxi',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
